package listbyorder.access001_100.test43;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/5/31 16:40
 */
public class Solution2 {

    // 300 斩答案  基本思路   时间复杂度较高
    // 遍历num1, 将每个位置的元素与num2进行相乘
    // 如果不是个位的元素，按照位数进行补0
    // 计算的结果与之前的结果进行累加
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) return "0";
        int index = 0;
        int len1 = num1.length();
        int len2 = num2.length();
        String res = "0";
        for (int i = len1 - 1; i >= 0; i--) {
            int c1 = num1.charAt(i) - '0';
            if (c1 != 0) {
                String cur_str = "";
                int carry = 0;
                for (int j = len2 - 1; j >= 0; j--) {
                    int c2 = num2.charAt(j) - '0';
                    int sum = c1 * c2 + carry;
                    cur_str = sum % 10 + "" + cur_str;
                    carry = sum / 10;
                }
                if (carry > 0) {
                    cur_str = carry + "" + cur_str;
                }
                for (int k = 0; k < index; k++) {
                    cur_str = cur_str + "0";
                }
                res = merger(res, cur_str);
            }
            index++;
        }
        return res;
    }

    private String merger(String s1, String s2) {
        String ans = "";
        int carry = 0;
        int c1 = s1.length() - 1;
        int c2 = s2.length() - 1;
        while (c1 >= 0 || c2 >= 0) {
            int v1 = c1 < 0 ? 0 : s1.charAt(c1) - '0';
            int v2 = c2 < 0 ? 0 : s2.charAt(c2) - '0';
            int sum = v1 + v2 + carry;
            carry = sum / 10;
            ans = sum % 10 + "" + ans;
            c1--;
            c2--;
        }
        if (carry > 0) {
            ans = carry + "" + ans;
        }
        return ans;
    }

}
